//
//  XFDateSelectView.m
//  WorkManager
//
//  Created by ukongm on 17/2/9.
//  Copyright © 2017年 ukongm. All rights reserved.
//


//所有关于day的字符串，都要处理成01形式


#import "XFDateSelectView.h"
/** 导航的高度 */
static CGFloat const NAVI_HEIGHT = 50;
/** 方块的高度 */
static CGFloat const ITEM_HEIGHT = 30;
/** 文字大小 */
static NSInteger const FONT_SIZE = 13;
/** 控件的起始TAG */
static NSInteger const BEGIN_TAG = 300;
/** 间距 */
static CGFloat const VIEW_GAP = 15;
/** 动画时间 */
static NSTimeInterval const TIME = 0.25;


/** 年份开始的时间 */
static NSInteger const BENGIN_YEAR = 1900;
/** 年份展示的跨度 */
static NSInteger const SCOPE_YEAR = 300;

@interface XFDateSelectView()<UITableViewDelegate,UITableViewDataSource>

/** 时间格式规范 */
@property(nonatomic,strong)NSDateFormatter* matter;

/** 导航 */
@property(nonatomic,strong)UIView* naviView;
/** 下一天 */
@property(nonatomic,strong)UIButton* nextBtn;
/** 前一天 */
@property(nonatomic,strong)UIButton* backBtn;

/** 缓存 */
@property(nonatomic,strong)NSMutableArray<DateView*>* dateViews;
/** 滚动视图 */
@property(nonatomic,strong)UIScrollView* scrollView;

/** 遮罩 */
@property(nonatomic,strong)UIView* backView;

/** 选择年份的view */
@property(nonatomic,strong)UILabel* yearLb;
/** 选择day的view */
@property(nonatomic,strong)UILabel* dayLb;
/** 上面两个的容器 */
@property(nonatomic,strong)UIView* selectView;
/** 选择年份 */
@property(nonatomic,strong)UITableView* tableView;

@end

@implementation XFDateSelectView
{
    CGRect _frame; //开始的位置
    void (^_block)(NSDate *);
    UILabel* _titleLb; //标题
    UIButton* _fixedBtn; //确定按钮
}
@synthesize curTime = _curTime;

#pragma mark - 中间选择视图(包括切换视图的逻辑)
- (UIView *)selectView{
    
    if (_selectView == nil) {
        _selectView = [[UIView alloc] initWithFrame:CGRectMake(VIEW_GAP, self.naviView.maxY + VIEW_GAP/2, self.width - 2 * VIEW_GAP, 60)];
        
        _selectView.layer.cornerRadius = 3;
        _selectView.layer.masksToBounds = YES;
        
        _selectView.backgroundColor = [UIColor pinkColor];
        
        [_selectView addSubview:self.yearLb];
        [_selectView addSubview:self.dayLb];
        
        [self setSelectType:NO time:0];
    }
    return _selectView;
}

- (UILabel *)yearLb{
    
    if (_yearLb == nil) {
        _yearLb = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_GAP, 0, self.selectView.width - VIEW_GAP * 2, self.selectView.height/2)];
        
        _yearLb.font = [UIFont boldSystemFontOfSize:18];
        _yearLb.userInteractionEnabled = YES;
        [_yearLb addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectYearAction)]];
    }
    return _yearLb;
}

- (UILabel *)dayLb{
    
    if (_dayLb == nil) {
        _dayLb = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_GAP, self.yearLb.maxY, self.yearLb.width, self.yearLb.height)];
        
        _dayLb.font = [UIFont boldSystemFontOfSize:20];
        _dayLb.userInteractionEnabled = YES;
        [_dayLb addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectDateAction)]];
    }
    return _dayLb;
}

- (void)selectYearAction{
    [self setSelectType:YES];
}

- (void)selectDateAction{
    [self setSelectType:NO];
}

//显示对应的信息，由下面设置date的时候调用
- (void)showSelectViewForDate:(NSDate*)curDate{
    self.matter.dateFormat = @"yyyy-MM 月 dd 日   EEEE";
    NSString* dateStr = [self.matter stringFromDate:curDate];
    NSArray* temp = [dateStr componentsSeparatedByString:@"-"];
    NSString* year = [temp firstObject];
    NSString* day = [temp lastObject];
    self.yearLb.text = year;
    self.dayLb.text = day;
}

//根据year字符串，返回对应的时间
- (NSDate*)dateForYearString:(NSString*)year{
    self.matter.dateFormat = @"yyyy-MM 月 dd 日   EEEE";
    NSString* dayStr = self.dayLb.text;
    NSString* yearStr = [NSString stringWithFormat:@"%@-%@",year,dayStr];
    return [self.matter dateFromString:yearStr];
}

//设置上面selectView中的选中状态
- (void)setSelectType:(BOOL)isYear{
    [self setSelectType:isYear time:TIME];
}

- (void)setSelectType:(BOOL)isYear time:(NSTimeInterval)time{
    CGFloat dateAlpha = 0;
    CGFloat yearAlpha = 0;
    
    if (isYear) {
        yearAlpha = 1;
        dateAlpha = 0;
        self.yearLb.textColor = [UIColor whiteColor];
        self.dayLb.textColor = [UIColor red:238 green:238 blue:238];
    }else{
        yearAlpha = 0;
        dateAlpha = 1;
        self.yearLb.textColor = [UIColor red:238 green:238 blue:238];
        self.dayLb.textColor = [UIColor whiteColor];
    }
    
    [UIView animateWithDuration:time animations:^{
        self.scrollView.alpha = dateAlpha;
        self.tableView.alpha = yearAlpha;
    }];
}

#pragma mark - 选择年份的逻辑
- (UITableView *)tableView{
    
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.selectView.x, self.selectView.maxY + VIEW_GAP/2, self.selectView.width, self.height - (self.selectView.maxY + VIEW_GAP))];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor red:238 green:238 blue:238];
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return SCOPE_YEAR;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString* cellID = @"year";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    NSString* value = XFIntegerToString(BENGIN_YEAR + indexPath.row);
    
    cell.textLabel.text = value;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.textColor = [UIColor lightGrayColor];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self setSelectType:NO];
    
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    
    NSDate* date = [self dateForYearString:cell.textLabel.text];
    [self showSelectViewForDate:date];
    self.showDate = date;
}

//选中的一个年份
- (void)setSelectYear:(NSString*)year{
    NSInteger index = (year.integerValue - BENGIN_YEAR);
    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}

#pragma mark - 日历

- (UIView *)naviView{
    
    if (_naviView == nil) {
        CGFloat gap = VIEW_GAP;
        CGFloat width = 50;
        _naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, NAVI_HEIGHT)];
        _naviView.backgroundColor = [UIColor whiteColor];
        
        _titleLb = [[UILabel alloc] initWithFrame:_naviView.bounds];
        _titleLb.font = [UIFont systemFontOfSize:15];
        _titleLb.textColor = [UIColor red:30 green:30 blue:30];
        _titleLb.textAlignment = NSTextAlignmentCenter;
        
        UIButton* cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(gap, 0, width, _naviView.height)];
        cancelBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
        
        _fixedBtn = [[UIButton alloc] initWithFrame:CGRectMake(_naviView.width - gap - width, 0, width, _naviView.height)];
        _fixedBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [_fixedBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_fixedBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_fixedBtn addTarget:self action:@selector(fixedAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_naviView addSubview:_titleLb];
        [_naviView addSubview:cancelBtn];
        [_naviView addSubview:_fixedBtn];
    }
    return _naviView;
}

- (UIView *)backView{
    
    if (_backView == nil) {
        _backView = [[UIView alloc] initWithFrame:CGRectZero];
        _backView.alpha = 0;
        _backView.backgroundColor = [UIColor blackColor];
        [_backView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)]];
    }
    return _backView;
}

- (UIScrollView *)scrollView{
    
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(VIEW_GAP, self.selectView.maxY, self.width - VIEW_GAP * 2, self.height - self.selectView.maxY)];
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;
        
        for (NSInteger i = 0; i < 3; i++) {
            CGRect frame = CGRectMake(i * _scrollView.width, 0, _scrollView.width, _scrollView.height);
            DateView* dateView = [[DateView alloc] initWithFrame:frame];
//            dateView.backgroundColor = [UIColor red:238 green:238 blue:238];
            [dateView setChangeCurTimeComplate:^(NSDate * newDate) {
                self.curDate = newDate;
            }];
            
            [self.dateViews addObject:dateView];
            [_scrollView addSubview:dateView];
        }
        
        [_scrollView setContentSize:CGSizeMake(_scrollView.width * self.dateViews.count, 0)];
        [_scrollView setContentOffset:CGPointMake(_scrollView.width, 0)];
    }
    return _scrollView;
}

- (UIButton *)nextBtn{
    
    if (_nextBtn == nil) {
        CGFloat size = 40;
        CGFloat x = self.width - size - VIEW_GAP;
        _nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(x, self.scrollView.y, size, size)];
        [_nextBtn setTitle:@"➡️" forState:UIControlStateNormal];
        [_nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}

- (UIButton *)backBtn{
    
    if (_backBtn == nil) {
        CGFloat size = 40;
        CGFloat x = VIEW_GAP;
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(x, self.scrollView.y, size, size)];
        [_backBtn setTitle:@"⬅️" forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}


- (NSMutableArray *)dateViews{
    
    if (_dateViews == nil) {
        _dateViews = [NSMutableArray new];
    }
    return _dateViews;
}

- (NSDateFormatter *)matter{
    
    if (_matter == nil) {
        _matter = [NSDateFormatter new];
    }
    return _matter;
}
#pragma mark ------ 初始化方法

- (instancetype)init
{
    CGFloat width = self.screenSize.width * 0.9;
    CGFloat height = 380;
    CGFloat x = (self.screenSize.width - width)/2;
    CGFloat y = self.screenSize.height;
    
    _frame = CGRectMake(x, y, width, height);
    
    
    return [self initWithFrame:_frame];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        [self addSubview:self.naviView];
        [self addSubview:self.selectView];
        [self addSubview:self.scrollView];
        [self addSubview:self.backBtn];
        [self addSubview:self.nextBtn];
        [self addSubview:self.tableView];
        self.layer.cornerRadius = 3;
        self.layer.masksToBounds = YES;
        self.backgroundColor = [UIColor red:238 green:238 blue:238];
    }
    return self;
}

#pragma mark - 显示影藏等方法

- (void)showInView:(UIView *)view andFixedComplate:(void (^)(NSDate *))fixedBlock{
    
    _block = fixedBlock;
    
    [view addSubview:self.backView];
    self.backView.frame = view.bounds;
    [view addSubview:self];
    
    if (self.curDate == nil) {
        self.curDate = [NSDate new];
    }else{
        self.curDate = self.curDate;
    }
    
    if (self.showDate == nil) {
        self.showDate = [NSDate new];
    }else{
        self.showDate = self.showDate;
    }
    
    [self setSelectYear:XFStringForDate(self.showDate, @"yyyy")];
    
    self.center = view.center;
    
    self.transform = CGAffineTransformMakeScale(0, 0);
    
    [UIView animateWithDuration:TIME animations:^{
        
        self.transform = CGAffineTransformIdentity;
        
        self.backView.alpha = 0.8;
    }];
    
}

- (void)hide{
    
    self.transform = CGAffineTransformIdentity;
    
    [UIView animateWithDuration:TIME animations:^{
        self.transform = CGAffineTransformMakeScale(0.001, 0.001);
        self.backView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.backView removeFromSuperview];
        [self removeFromSuperview];
    }];
}

- (void)fixedAction{
    if (_block) {
        if (self.curDate) {
            _block(self.curDate);
        }else{
            _block([NSDate new]);
        }
    }
    
    [self hide];
}

#pragma mark 设置信息
- (void)setTitle:(NSString *)title{
    _title = title;
    
    _titleLb.text = title;
}

- (void)setDate:(NSDate *)date{
    if (date == nil) {
        date = [NSDate new];
    }
    _curDate = date;
    _showDate = date;
}

- (void)setCurDate:(NSDate *)curDate{
    _curDate = curDate;
    
    [self.dateViews enumerateObjectsUsingBlock:^(DateView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       [obj reset];
        obj.curDate = curDate;
        
    }];
    
    _curTime = [curDate timeIntervalSince1970];
    //获取年份和时间，供展示
    [self showSelectViewForDate:curDate];
}

- (void)setShowDate:(NSDate *)showDate{
    _showDate = showDate;
    
    [self mathChangeShow:0 date:showDate];
}

- (void)setCurTime:(NSTimeInterval)curTime{
    
    if (curTime == 0) {
        curTime = [[NSDate new] timeIntervalSince1970];
    }
    
    _curTime = curTime;
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:curTime];
    
    self.curDate = date;
}

- (void)setCurrentYear:(NSString *)year month:(NSString *)month{
    [self setCurrentYear:year month:month day:@"01"];
}

- (void)setCurrentYear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    NSString* dateStr = [NSString stringWithFormat:@"%@-%@",year,month];
    
    self.matter.dateFormat = @"yyyy-MM";
    
    NSDate* date = [self.matter dateFromString:dateStr];
    
    if (day) {
        self.matter.dateFormat = @"yyyy-MM-dd";
        dateStr = [dateStr stringByAppendingString:[NSString stringWithFormat:@"-%@",day]];
        date = [self.matter dateFromString:dateStr];
    }
    
    if (!date) {
        [self setCurrentYear:year month:month];
        return;
    }
    
    self.curDate = date;
}

#pragma mark - 切换视图的方法
- (NSDate*)setShowYear:(NSString *)year month:(NSString *)month dateView:(DateView*)dateView{
    
    NSInteger moon = month.integerValue;
    
    if (moon > 12) {
        moon = moon % 12;
    }
    
    month = [NSString stringWithFormat:@"%02ld",moon];
    
    NSString* dateStr = [NSString stringWithFormat:@"%@-%@",year,month];
    
    self.matter.dateFormat = @"yyyy-MM";
    
    NSDate* date = [self.matter dateFromString:dateStr];
    
    dateView.showDate = date;
    
    return date;
}

#pragma mark 切换日期的主要逻辑(type = 0 当前showdate显示   1 当前showDate的下一个月)
- (void)mathChangeShow:(NSInteger)type date:(NSDate*)date{
    
    self.matter.dateFormat = @"yyyy-MM";
    NSString* dateStr = [self.matter stringFromDate:date];
    NSArray* dateArray = [dateStr componentsSeparatedByString:@"-"];
    
    NSString* year = [dateArray firstObject];
    __block NSString* moonStr = [dateArray lastObject];
    
    NSInteger moon = moonStr.integerValue;
    moon = moon + type - 1;
    
    if (moon == -1) {
        moon = 11;
    }
    
    if (moon > 12) {
        moon = 1;
    }
    
    if (moon < 1) {
        moon = 12;
    }
    
    [self.dateViews enumerateObjectsUsingBlock:^(DateView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        
        moonStr = [NSString stringWithFormat:@"%02ld",moon + idx];
        
        
        [obj reset];
        
        
        NSDate* date = [self setShowYear:year month:moonStr dateView:obj];
        
        if (idx == 1) {
            
            _showDate = date;
        }
        
    }];
    
}


#pragma mark 点击按钮切换上一月和下一月
- (void)nextAction{
    
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.width * 2, 0) animated:YES];
}

- (void)backAction{
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark 滚动时候的复用逻辑
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView == self.scrollView) {
        if (scrollView.contentOffset.x == 0) {
            //上一个月
            [self mathChangeShow:-1 date:self.showDate];
            [scrollView setContentOffset:CGPointMake(scrollView.width, 0)];
        }else if (scrollView.contentOffset.x == scrollView.width * 2){
            //下一个月
            [self mathChangeShow:1 date:self.showDate];
            [scrollView setContentOffset:CGPointMake(scrollView.width, 0)];
        }
    }
}

@end





@interface DateView()

/** 复用cache */
@property(nonatomic,strong)NSMutableDictionary* cache;
/** 顶部的week信息 */
@property(nonatomic,strong)UIView* weekView;
/** 上次选中的label */
@property(nonatomic,strong)UILabel* pastLb;
/** 文字选中的颜色 */
@property(nonatomic,strong)UIColor* sel_font_color;
/** 文字默认的颜色 */
@property(nonatomic,strong)UIColor* nor_font_color;
/** 默认背景 */
@property(nonatomic,strong)UIColor* nor_back_color;
/** 选中背景 */
@property(nonatomic,strong)UIColor* sel_back_color;


/** 提示文字 */
@property(nonatomic,strong)UILabel* hintLb;

@end

@implementation DateView
{
    NSDate* _pastDate;
}

@synthesize showDate = _showDate;

- (UIColor *)sel_back_color{
    return [UIColor pinkColor];
}

- (UIColor *)nor_back_color{
    return [UIColor clearColor];
}

- (UIColor *)sel_font_color{
    return [UIColor whiteColor];
}

- (UIColor *)nor_font_color{
    return [UIColor red:100 green:100 blue:100];
}

- (UILabel *)hintLb{
    
    if (_hintLb == nil) {
        _hintLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.width, 40)];
        _hintLb.font = [UIFont systemFontOfSize:14];
        _hintLb.textAlignment = NSTextAlignmentCenter;
    }
    return _hintLb;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.hintLb];
        [self addSubview:self.weekView];
    }
    return self;
}

- (NSArray*)weeks{
    return @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
}


- (UIView *)weekView{
    
    if (_weekView == nil) {
        _weekView = [[UIView alloc] initWithFrame:CGRectMake(0, self.hintLb.maxY, self.width, ITEM_HEIGHT * 1.2)];
        
        NSInteger lineCount = self.weeks.count;
        CGFloat width = self.width / lineCount;
        
        for (NSInteger i = 0; i < lineCount; i++) {
            
            UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(i * width, 0, width, _weekView.height)];
            
            label.textAlignment = NSTextAlignmentCenter;
            
            label.backgroundColor = self.nor_back_color;
            
            label.font = [UIFont systemFontOfSize:FONT_SIZE];
            
            label.text = self.weeks[i];
            
            [_weekView addSubview:label];
        }
    }
    return _weekView;
}

- (NSMutableDictionary *)cache{
    
    if (_cache == nil) {
        _cache = [NSMutableDictionary new];
    }
    return _cache;
}

- (NSDate *)curDate{
    if (_curDate == nil) {
        _curDate = [NSDate new];
    }
    return _curDate;
}

#pragma mark - 设置相关信息
- (void)setShowDate:(NSDate *)showDate{
    _showDate = showDate;
    
    [self changeView:showDate];
}

- (void)changeView:(NSDate*)showDate{
    [self math:showDate];
    
    if (self.curDate) {
        //判断是不是同一个月，是的话 为0
        NSInteger reuslt = [self compareDate:showDate date:self.curDate];
        
        if (reuslt == 0) {
            //当前显示的就是选中的月份，开始进行画选中day
            NSString* key = [self getDayForDate:self.curDate];
            
            [self selectViewForKey:key];
        }
    }
    
    self.hintLb.text = [self date:showDate formatter:@"yyyy 年 MM 月"];
}

- (void)math:(NSDate*)date{
//    [self reset];
    NSInteger day = [self mathDayForMonth:date];
    NSInteger firstDateWeek = [self mathWeekForCurrentMonthOneDay:date] - 1;
    [self createViewForDay:day firstDayWeek:firstDateWeek];
}

//计算date当月的天数
- (NSInteger)mathDayForMonth:(NSDate*)date{
    //1.获取当月的总天数
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    NSUInteger numberOfDaysInMonth = range.length;
    
    return numberOfDaysInMonth;
}

//计算date当月第一天是星期几
- (NSInteger)mathWeekForCurrentMonthOneDay:(NSDate*)date{
    
    NSDateFormatter* matter = [NSDateFormatter new];
    matter.dateFormat = @"yyyy-MM";
    NSString* dateStr = [matter stringFromDate:date];
    dateStr = [dateStr stringByAppendingString:@"-01"];
    matter.dateFormat = @"yyyy-MM-dd";
    NSDate* newDate = [matter dateFromString:dateStr];
    
    return [self mathWeekForCurrentDate:newDate];
}

//获取curDate当天是星期几
- (NSInteger)mathWeekForCurrentDate:(NSDate*)curDate{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:curDate];
    
    return theComponents.weekday;
}


/**
 根据本月的天数和本月第一天的星期几，来创建控件

 @param day  date的天数
 @param week date月份的第一天的星期几
 */
- (void)createViewForDay:(NSInteger)day firstDayWeek:(NSInteger)week{
    
//    [self reset];
    [self.cache.allValues makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    NSInteger lineCount = self.weeks.count;
    CGFloat gap = 0;
    CGFloat width = (self.width - (lineCount + 1) * gap) / lineCount;
    CGFloat height = ITEM_HEIGHT;
    
    for (NSInteger i = 1; i <= day; i++) {
        
        NSString* key = [NSString stringWithFormat:@"%02ld",i];
        
        NSInteger curI = i + week - 1;
        
        NSInteger cod = curI % lineCount;
        NSInteger row = curI / lineCount;
        
        CGRect frame = CGRectMake(cod * (width + gap) + gap, row * height + self.weekView.maxY, width, height);
        
        UILabel* label = [self getViewForKey:key];
        
        label.frame = frame;
        
        label.text = key;
        
        [self addSubview:label];
    }
}

- (UILabel*)getViewForKey:(NSString*)key{
    
    UILabel* label = [self.cache objectForKey:key];
    
    if (!label) {
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        
        label.textAlignment = NSTextAlignmentCenter;
        
        label.font = [UIFont systemFontOfSize:FONT_SIZE];
        
        label.tag = BEGIN_TAG + key.integerValue;
        
        label.backgroundColor = self.nor_back_color;
        
        label.textColor = self.nor_font_color;
        
        label.userInteractionEnabled = YES;
        
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelAction:)]];
        
        [self.cache setObject:label forKey:key];
    }
    
    return label;
}


- (void)selectViewForKey:(NSString*)key{
    
    UILabel* label = [self.cache objectForKey:key];
    
    if (label == nil) {
        return;
    }
    
    if (label == self.pastLb) {
        return;
    }
    
    self.pastLb.backgroundColor = self.nor_back_color;
    self.pastLb.textColor = self.nor_font_color;
    
    label.backgroundColor = self.sel_back_color;
    label.textColor = self.sel_font_color;
    
    self.pastLb = label;
}

- (void)labelAction:(UITapGestureRecognizer*)tap{
    UILabel* label = (UILabel*)tap.view;
    NSString* key = label.text;
//    self.curDay = index;
    self.curDate = [self dateWithDate:self.showDate newDay:key];
    
    if (self.changeCurTimeComplate) {
        self.changeCurTimeComplate(self.curDate);
    }
    
    [self selectViewForKey:key];
}

- (void)reset{
    self.pastLb.backgroundColor = self.nor_back_color;
    self.pastLb.textColor = self.nor_font_color;
    self.pastLb = nil;
//    self.curDate = nil;
}

#pragma mark 工具方法

/**
 比较两个时间（
    -1 ： 1 《 2
    0 ： 1 = 2
    1 ： 1 》 2）
只比较 年份和月份， 不比较天数
 
 @param date1 时间1
 @param date2 时间2
 */
- (NSInteger)compareDate:(NSDate*)date1 date:(NSDate*)date2{
    NSDateFormatter* matter = [NSDateFormatter new];
    matter.dateFormat = @"yyyy-MM";
    //date1的数据
    NSArray* array = [[matter stringFromDate:date1] componentsSeparatedByString:@"-"];
    NSInteger year1 = [[array firstObject] integerValue];
    NSInteger moon1 = [[array lastObject] integerValue];
    //date2的数据
    array = [[matter stringFromDate:date2] componentsSeparatedByString:@"-"];
    NSInteger year2 = [[array firstObject] integerValue];
    NSInteger moon2 = [[array lastObject] integerValue];
    
    if (year1 == year2) {
        //比较月份
        if (moon1 == moon2) {
            return 0;
        }else if (moon1 < moon2){
            return -1;
        }else{
            return 1;
        }
    }else{
        if (year1 < year2) {
            return -1;
        }else{
            return 1;
        }
    }
}

/* 根据date获取 day , 对应获取控件的key*/
- (NSString*)getDayForDate:(NSDate*)date{
    NSDateFormatter* matter = [NSDateFormatter new];
    matter.dateFormat = @"yyyy-MM-dd";
    
    return [[[matter stringFromDate:date] componentsSeparatedByString:@"-"] lastObject];
}


/**
 把date中的day，替换成新的day

 @param date   date
 @param newDay 新的day

 @return 时间对象
 */
- (NSDate*)dateWithDate:(NSDate*)date newDay:(NSString*)newDay{
    NSDateFormatter* matter = [NSDateFormatter new];
    matter.dateFormat = @"yyyy-MM-dd";
    
    NSString* string = [matter stringFromDate:date];
    NSArray* array = [string componentsSeparatedByString:@"-"];
    
    NSMutableArray* temp = [NSMutableArray arrayWithArray:array];
    [temp removeLastObject];
    [temp addObject:newDay];
    string = [temp componentsJoinedByString:@"-"];
    
    return [matter dateFromString:string];
}


/**
 根据date和格式符，转化成字符串

 @param date   daye
 @param matterStr 格式符

 @return 返回字符串
 */
- (NSString*)date:(NSDate*)date formatter:(NSString*)matterStr{
    NSDateFormatter* matter = [NSDateFormatter new];
    matter.dateFormat = matterStr;
    
    return [matter stringFromDate:date];
}


@end
